import { defineStore } from 'pinia'
import { CHAT_MODE_TYPE } from '@/contants/message'

const state = () => ({
  // 聊天模式： 语音/文字/表情/扩展菜单
  currentChatMode: CHAT_MODE_TYPE.KEYBOARD,
  // 全局唯一录音管理器
  recorder: null,
  // 录音时长
  recorderTime: 0,
  // 录音定时器
  recorderTimer: null,
  // 发送语音函数
  sendVoice: null,
  // 聊天对象
  chatOther: {}
})

const actions = {
  initRecorder() {
    // 创建录音管理器
    this.recorder = uni.getRecorderManager()

    // 开启录音
    this.recorder.onStart(() => {
      this.recorderTime = 0
      this.recorderTimer = setInterval(() => {
        this.recorderTime++
      }, 1000)
    })

    // 结束录音
    this.recorder.onStop((res) => {
      if (this.recorderTime < 1)
        return uni.showToast({
          title: '录音时间太短',
          icon: 'none'
        })
      if (this.recorderTimer) {
        clearInterval(this.recorderTimer)
        this.recorderTimer = null
      }
      if (typeof this.sendVoice === 'function') {
        // 发送消息
        this.sendVoice(res.tempFilePath)
      }
    })
  },
  // 注册发送语音的事件(函数)
  registerSendVoiceEvent(eventFn) {
    this.sendVoice = eventFn
  },
  // 设置聊天模式
  setCurrentChatMode(mode) {
    this.currentChatMode = mode
  },
  // 设置聊天对象
  setChatOther(chatOther) {
    this.chatOther = chatOther
  }
}

export const useChatStore = defineStore('chat', {
  state,
  actions
})
